using System;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using BSDS.Core.Model.Services.Jobs;
using BSDS.Core.Model.Services.Jobs.Core;

namespace BSDS.Core.Data.Remote.Upload
{
    public class UploadResponseParser : ResponseParserBase
    {
        public JobState ParseGetStatusResponse(string jobId, string response)
        {
            const string xmlns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

            var document = XDocument.Parse(response);

            var statusValue = document.Descendants(XName.Get("DataflowJob", xmlns))
                           .Select(l => l.Element(XName.Get("Status", xmlns)))
                           .First().Value;
            var successLink = GetLink(document, xmlns, "dataSource");
            var failureLink = GetLink(document, xmlns, "failed");
            var completedDate = GetCompletionDate(document, xmlns);

            var status = (JobStatus)Enum.Parse(typeof(JobStatus), statusValue);

            var complitionStatus = successLink == null ? JobComplitionStatus.Failure : JobComplitionStatus.Success;
            var result = new JobResult(complitionStatus, successLink, failureLink);

            return new JobState(jobId, status, result, 
                status == JobStatus.Aborted ? response : string.Empty, completedDate);
        }

        public UploadJob ParseCreateUploadJobResponse(string response)
        {
            const string xmlns = "http://schemas.microsoft.com/search/local/ws/rest/v1";

            var document = XDocument.Parse(response);

            return document.Descendants(XName.Get("DataflowJob", xmlns))
                           .Select(job => new UploadJob
                           {
                               Id = job.Element(XName.Get("Id", xmlns)).Value.Trim(),
                               Link = job.Element(XName.Get("Link", xmlns)).Value.Trim(),
                               SubmissionDate = DateTime.Parse(job.Element(XName.Get("CreatedDate", xmlns)).Value.Trim())
                           }).First();
        }

    }
}